package com.uzai.console.service.pyq.impl;

import com.alibaba.fastjson.JSONObject;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.BeanMapUtil;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.entity.PyqJob;
import com.uzai.console.entity.es.PyqJobDetail;
import com.uzai.console.mapper.PyqJobMapper;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.UzaiBusinessFeignService;
import com.uzai.console.service.feign.dto.GoodsUpdateExposureNumBySendPyqDto;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.pyq.PyqJobDetailService;
import com.uzai.console.service.pyq.PyqJobSyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 发送朋友圈异步执行线程
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class PyqJobSyncServiceImpl implements PyqJobSyncService {

    Logger logger = LoggerFactory.getLogger(PyqJobSyncServiceImpl.class);

    @Autowired
    private PyqJobMapper pyqJobMapper;
    @Autowired
    private PyqJobDetailService pyqJobDetailService;
    @Autowired
    private UzaiBusinessFeignService uzaiBusinessFeignService;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;

    /**
     * 添加朋友圈发送
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param pyqJob
     * @return null
     */
    @Override
    @Async("taskExecutor")
    public void addJobSync(PyqJob pyqJob, List<Long> deviceUniqueIdList, Long domain){

        //首先朋友圈个数为0
        pyqJob.setTotalCount(0);

        List<PyqJobDetail> pyqJobDetailList = new ArrayList<>();

        //查询所有机器人
        for(Long deviceUniqueId : deviceUniqueIdList){
            try{
                PyqJobDetail pyqJobDetail = pyqJobDetailService.sendPyqJobDetailSync(pyqJob, deviceUniqueId, domain);
                if(pyqJobDetail != null){
                    pyqJobDetailList.add(pyqJobDetail);
                }
            }catch (Exception e){
                logger.error("----发送朋友朋友圈明细错误---",e);
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, e.getMessage());
            }
        }

        if(pyqJobDetailList != null && pyqJobDetailList.size() > 0){
            // UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.pyqMsgPush(pyqJobDetailList);
            //elasticsearchUtil.addData(JSONObject.parseObject(JSONObject.toJSONString(pyqJobDetail)), EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJobDetail.getId());
            String uzai_pyq_job_detail = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJob.getMerId());
            //保存发送消息
            List<Map<String, Object>> list = BeanMapUtil.objectList2ListMap(pyqJobDetailList);
            boolean result = elasticsearchUtilGroupMsg.addDataBatch(list, uzai_pyq_job_detail);
            logger.info("添加朋友圈明细完成---, 主任务id={}, result={}", pyqJob.getId(), JSONObject.toJSONString(result));
            //发送成功则朋友圈数量增加1
            if(result){
                pyqJob.setTotalCount(pyqJobDetailList.size());
                //如果是精品库商品，增加曝光率
                try {
                    if(pyqJob.getType().intValue() == 2 || pyqJob.getType().intValue() == 3){ //悠哉精品库发送成功，增加曝光量
                        GoodsUpdateExposureNumBySendPyqDto goodsUpdateExposureNumBySendPyqDto = new GoodsUpdateExposureNumBySendPyqDto();
                        goodsUpdateExposureNumBySendPyqDto.setId(pyqJob.getJpkGoodsId());
                        goodsUpdateExposureNumBySendPyqDto.setAddNum(1);
                        UzaiRespVo<Object> uzaiRespVo1 = uzaiBusinessFeignService.updateExposureNumBySendPyq(goodsUpdateExposureNumBySendPyqDto);
                        logger.info("---修改悠哉精品库商品转发朋友圈曝光量，para={}, result={}",JSONObject.toJSONString(goodsUpdateExposureNumBySendPyqDto), JSONObject.toJSONString(uzaiRespVo1));
                    }
                }catch (Exception e){

                }
            }
            //logger.info("---完成添加朋友圈发送明细----，准备添加发送任务");
            //添加发送任务
            if(pyqJob.getTotalCount().intValue() > 0){
                pyqJobMapper.insert(pyqJob);
            }
        }
    }

    /**
     * 修改群发任务
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param pyqJob
     * @return null
     */
    @Override
    public void  updateJobSync(PyqJob pyqJob, List<Long> deviceUniqueIdList, Long domain){

        //首先朋友圈个数为0
        pyqJob.setTotalCount(0);

        List<PyqJobDetail> pyqJobDetailList = new ArrayList<>();

        for(Long deviceUniqueId : deviceUniqueIdList){
            try{
                PyqJobDetail pyqJobDetail = pyqJobDetailService.sendPyqJobDetailSync(pyqJob, deviceUniqueId, domain);
                if(pyqJobDetail != null){
                    pyqJobDetailList.add(pyqJobDetail);
                }
            }catch (Exception e){

            }
        }

        if(pyqJobDetailList != null && pyqJobDetailList.size() > 0){
            // UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.pyqMsgPush(pyqJobDetailList);
            //elasticsearchUtil.addData(JSONObject.parseObject(JSONObject.toJSONString(pyqJobDetail)), EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJobDetail.getId());
            String uzai_pyq_job_detail = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJob.getMerId());
            //保存发送消息
            List<Map<String, Object>> list = BeanMapUtil.objectList2ListMap(pyqJobDetailList);
            boolean result = elasticsearchUtilGroupMsg.addDataBatch(list, uzai_pyq_job_detail);
            logger.info("修改朋友圈明细完成---, 主任务id={}, result={}", pyqJob.getId(), JSONObject.toJSONString(result));
            //发送成功则朋友圈数量增加1
            if(result){
                pyqJob.setTotalCount(pyqJobDetailList.size());
            }
        }
        //修改发送任务
        pyqJobMapper.updateById(pyqJob);

    }

}
